<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="课程名称" prop="courseName">
                <el-input
                    v-model="queryParams.courseName"
                    placeholder="请输入课程名称"
                    clearable
                    size="small"
                    style="width: 180px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="课程学期" prop="courseTerm">
                <el-select
                    v-model="queryParams.courseTerm"
                    placeholder="课程学期"
                    clearable
                    size="small"
                    style="width: 180px">
                    <el-option
                        v-for="dict in termOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增</el-button>
            </el-col>
        </el-row>

        <!-- @selection-change="handleSelectionChange" -->
        <el-table v-loading="loading"
                row-key="id"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                :data="courseList">
            <!-- <el-table-column type="selection" width="40" align="center" /> -->
            <el-table-column label="课程名称" align="center" prop="courseName"/>
            <el-table-column label="课程编号" align="center" prop="courseNo"/>
            <el-table-column label="课程类型" align="center" prop="courseType" :formatter="courseTypeFormat"/>
            <el-table-column label="章节编号" align="center" prop="sectionNo"/>
            <el-table-column label="章节名称" align="center" prop="courseSection"/>
            <el-table-column label="专业" align="center" prop="subjectName"/>
            <el-table-column label="学期" align="center" :formatter="courseTermFormat"/>
            <el-table-column label="状态" align="center" >
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
                        @change="handleStatusChange(scope.row)"/>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="180" >
                <template slot-scope="scope">
                  <el-button size="mini" circle type="success" icon="el-icon-edit" @click="handleUpdate(scope.row)"/>
                  <el-button size="mini" circle type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"/>
                </template>
            </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- add -->
    <el-dialog :title="title" :visible.sync="open" width="30%">
        <el-form :model="form" ref="form" :rules="rules" label-width="90px">
            <el-form-item label="课程名称" prop="courseName">
                <el-input v-model="form.courseName"/>
            </el-form-item>
            <el-form-item label="课程类型" prop="courseType">
              <el-select v-model="form.courseType" placeholder="请选择课程类型" style="width: 100%;">
                <el-option v-for="item in courseTypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="所属专业" prop="subjectId">
              <el-select v-model="form.subjectId" placeholder="请选择所属专业" style="width: 100%;">
                <el-option v-for="item in subjectOptions" :key="item.id" :label="item.subjectName" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="课程学期" prop="courseTerm">
              <el-select v-model="form.courseTerm" placeholder="请选择课程学期" style="width: 100%;">
                <el-option v-for="item in termOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label="课程章节数" prop="courseNo">
                <el-input-number v-model="form.courseNo" @change="inputCourseSections" :min="0" :max="100" ></el-input-number>
            </el-form-item>
            <el-form-item label="课程章节" v-if="sectionList.length>0">
                <div v-for="item in sectionList" :key="item.sectionNo">
                    <el-input size="mini" v-model="item.courseSection"  style="width:100%" >
                        <template slot="prepend">{{item.sectionNo}}</template>
                    </el-input>
                </div>
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-switch v-model="form.status" active-value="1" inactive-value="0"/>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

    <!-- 修改章节 -->
    <el-dialog :title="sectionTitle" :visible.sync="sectionUpdateOpen" width="35%">
        <el-form :model="sectionUpdateForm" ref="sectionUpdateForm"  label-width="90px">
            <el-form-item label="章节序号" prop="sectionNo">
                <el-input v-model="sectionUpdateForm.sectionNo"/>
            </el-form-item>
            <el-form-item label="章节名称" prop="courseSection">
                <el-input v-model="sectionUpdateForm.courseSection"/>
            </el-form-item>

            <el-row :gutter="10" class="mb8">
                <el-col :span="12">
                    <el-form-item label="课程学期" prop="courseTerm" label-width="90px">
                        <el-select
                            v-model="sectionUpdateForm.courseTerm"
                            placeholder="请选择"
                            clearable
                            size="small"
                        >
                        <el-option
                            v-for="item in termOptions"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        >
                        </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否启用" prop="status">
                        <el-switch
                            v-model="sectionUpdateForm.status"
                            active-value="1"
                            inactive-value="0"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="sectionUpdateSubmitForm">确 定</el-button>
            <el-button @click="sectionCancel">取 消</el-button>
        </div>
    </el-dialog>
    </div>
</template>

<script>
import { listBCourse,createOrUpdateCourse,findAllCourseTerm, delBCourse } from "@/api/basedata/bcourse";
import { getSubjectListAll } from "@/api/basedata/bsubject"

export default {
    name: "BClass",
    data(){
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 弹出层标题
            title: "",
            sectionTitle: "",
            // 是否显示弹出层
            open: false,
            // 是否显示修改章节弹出层
            sectionUpdateOpen: false,
            //table数据
            courseList:[],
            // 专业
            subjectOptions: [],
            //课程学期数据字典
            termOptions:[],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                courseName: undefined,
                courseTerm: undefined,
            },
            // 表单参数
            form: {},
            // 章节表单参数
            sectionUpdateForm: {},
            // 表单校验
            rules:{
                courseName:[
                    { required: true, message: "课程名称必填", trigger: "blur" }
                ],
                courseType:[
                  {required: true, message: '请选择课程类型', trigger: 'change'}
                ],
                subjectId:[
                    { required: true, message: "请选择所属专业", trigger: "change" }
                ],
            },
            sectionList:[],

            courseTypeOptions : [], //课程类型字典数据
        }
    },
    created(){
      //获取课程类型字典数据
      this.getDicts("course_type").then(response => {
        this.courseTypeOptions = response.data;
      })

      this.getList();
      this.getCourseTermList();
      this.getSubjectList();
    },
    methods:{
        getSubjectList() {
            getSubjectListAll().then(resp => {
                this.subjectOptions = resp.data
            })
        },
        getList(){
            this.loading = true;
            listBCourse(this.queryParams).then(response => {
                this.courseList = response.data.list;
                this.total = response.data.total;
                this.loading = false;
            });
        },

        getCourseTermList(){
            findAllCourseTerm().then(resp => {
                this.termOptions = resp.data
            })
        },

        inputCourseSections(value) {
            const length = this.sectionList.length - value;

            if(length < 0) {
                for(var i = 0; i < Math.abs(length); i++){
                 this.sectionList.push({
                    sectionNo: this.sectionList.length + 1
                 })
                }
            } else {
                for(var i = 0; i < length; i++) {
                this.sectionList.pop();
                }
            }

        },

        courseTermFormat(row, column) {
            return this.selectDictLabel(this.termOptions, row.courseTerm);
        },
        courseTypeFormat(row, column) {
          return this.selectDictLabel(this.courseTypeOptions, row.courseType);
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.studentOptions = selection
            this.ids = selection.map(item => item.id)
            this.single = selection.length!==1
            this.multiple = !selection.length
        },

        handleStatusChange(row){
            for(let i = 0; i < row.children.length; i ++) {
                row.children[i].status = row.status;
            }
            createOrUpdateCourse(row)
        },

        handleAdd(){
            this.title = "新增课程"
            this.open = true;
            this.reset()
        },
        handleUpdate(row){
            console.log(row)
            if(row.courseSection != null) {
                // this.sectionUpdateReset();
                this. sectionTitle = "修改章节"
                this.sectionUpdateOpen = true;
                this.sectionUpdateForm = JSON.parse(JSON.stringify(row));
                // createOrUpdateCourse(row);
            } else {
                this.title = "修改课程"
                this.open = true;
                this.form = JSON.parse(JSON.stringify(row));
                if(row.children != null && row.children.length > 0) {
                    this.sectionList = row.children;
                } else {
                    this.sectionList = [];
                }

                // createOrUpdateCourse(row)
            }
        },
        handleDelete(row){
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除课程编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBCourse(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
        },
        reset() {
            this.form = {
                courseName: null,
                courseNo:null,
                courseTerm:null,
                status:"1",
            };
            this.sectionList = [];
            this.resetForm("form");
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        sectionCancel() {
            this.sectionUpdateOpen = false;
            this.sectionUpdateReset();
        },
        sectionUpdateReset() {
            console.log(this.sectionUpdateForm)
            this.sectionUpdateForm = {
                sectionNo: null,
                courseSection: null,
                courseTerm: null,
                status: "1"
            };
            this.resetForm("sectionUpdateForm");
        },
        submitForm:function(){
            this.$refs["form"].validate((valid) => {
                this.form.sectionList = this.sectionList;
                console.log(this.form)
                if (valid) {
                    createOrUpdateCourse(this.form).then((resp) => {
                        this.msgSuccess("提交成功");
                        this.open = false;
                        this.getList();
                    });
                }
            });
        },
        sectionUpdateSubmitForm:function(){
            this.$refs["sectionUpdateForm"].validate((valid) => {
                if (valid) {
                    createOrUpdateCourse(this.sectionUpdateForm).then((resp) => {
                        this.msgSuccess("提交成功");
                        this.sectionUpdateOpen = false;
                        this.getList();
                    });
                }
            });
        }
    }
}
</script>

<style scoped>
  .el-select .el-input {
    width: 130px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
